<template>
  <div class="test-reports-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">测试报告管理</h2>
        <p class="page-description">管理测试报告，查看测试执行情况和统计信息</p>
      </div>
    </div>

    <!-- 筛选和操作区域 -->
    <div class="filter-section">
      <el-card shadow="never">
        <div class="filter-row">
          <div class="filter-left">
            <el-input
              v-model="filterForm.search"
              placeholder="搜索报告名称..."
              clearable
              style="width: 300px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="filterForm.test_plan_id"
              placeholder="选择测试计划"
              clearable
              filterable
              style="width: 250px"
            >
              <el-option
                v-for="plan in testPlanOptions"
                :key="plan.id"
                :label="plan.name"
                :value="plan.id"
              />
            </el-select>
            <el-select
              v-model="filterForm.version_id"
              placeholder="选择版本（可选）"
              clearable
              filterable
              style="width: 250px"
            >
              <el-option
                v-for="version in versionOptions"
                :key="version.id"
                :label="`${version.version_number} - ${version.name}`"
                :value="version.id"
              />
            </el-select>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleResetFilter">重置</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 测试报告列表 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="testReports"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="name" label="报告名称" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)" :underline="false">
              {{ row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="test_plan_name" label="测试计划" width="200" />
        <el-table-column prop="version_name" label="关联版本" width="200">
          <template #default="{ row }">
            <span v-if="row.version_name">
              {{ row.version_number ? `${row.version_number} - ${row.version_name}` : row.version_name }}
            </span>
            <el-button
              v-else
              type="primary"
              size="small"
              text
              @click="handleLinkVersion(row)"
            >
              关联版本
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="generated_at" label="生成时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.generated_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="creator_name" label="创建人" width="120" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="handleView(row)">
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              text
              @click="handleLinkVersion(row)"
              v-if="!row.version_id"
            >
              关联版本
            </el-button>
            <el-button
              type="primary"
              size="small"
              text
              @click="handleUploadFile(row)"
            >
              上传文件
            </el-button>
            <el-button
              type="danger"
              size="small"
              text
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 关联版本对话框 -->
    <el-dialog
      v-model="linkVersionDialogVisible"
      title="关联版本"
      width="500px"
    >
      <el-form
        ref="linkVersionFormRef"
        :model="linkVersionForm"
        label-width="100px"
      >
        <el-form-item label="选择版本">
          <el-select
            v-model="linkVersionForm.version_id"
            placeholder="选择版本"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="version in versionOptions"
              :key="version.id"
              :label="`${version.version_number} - ${version.name}`"
              :value="version.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="linkVersionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveLinkVersion" :loading="linking">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 上传文件对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传报告文件"
      width="500px"
    >
      <el-upload
        ref="uploadRef"
        :action="uploadAction"
        :headers="uploadHeaders"
        :data="uploadData"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        :file-list="fileList"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 PDF、Word、Excel 等格式文件
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, UploadFilled } from '@element-plus/icons-vue'
import {
  getTestReports,
  deleteTestReport,
  linkVersion,
  type TestReportListResponse
} from '@/api/test-report'
import { getTestPlans } from '@/api/test-plan'
import { versionAPI } from '@/api/version'
import { formatDateTime } from '@/utils/date'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const testReports = ref<TestReportListResponse[]>([])
const testPlanOptions = ref<Array<{ id: string; name: string }>>([])
const versionOptions = ref<Array<{ id: string; name: string; version_number: string }>>([])

// 筛选表单
const filterForm = reactive({
  search: '',
  test_plan_id: '',
  version_id: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 对话框状态
const linkVersionDialogVisible = ref(false)
const uploadDialogVisible = ref(false)
const linking = ref(false)
const currentReport = ref<TestReportListResponse | null>(null)

// 关联版本表单
const linkVersionFormRef = ref()
const linkVersionForm = reactive({
  version_id: ''
})

// 上传相关
const uploadRef = ref()
const fileList = ref([])
const uploadAction = computed(() => {
  if (!currentReport.value) return ''
  return `/api/v1/test-reports/${currentReport.value.id}/upload`
})
const uploadHeaders = computed(() => {
  const token = userStore.token
  return token ? { Authorization: `Bearer ${token}` } : {}
})
const uploadData = computed(() => ({}))

// 加载数据
const loadTestReports = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      size: pagination.size
    }
    if (filterForm.search) {
      // 搜索功能需要后端支持
    }
    if (filterForm.test_plan_id) {
      params.test_plan_id = filterForm.test_plan_id
    }
    if (filterForm.version_id) {
      params.version_id = filterForm.version_id
    }

    const result = await getTestReports(params)
    testReports.value = result.items || []
    pagination.total = result.total || 0
    pagination.page = result.page || 1
    pagination.size = result.size || 20
  } catch (error: any) {
    console.error('加载测试报告失败:', error)
    ElMessage.error(error?.message || '加载测试报告失败')
    testReports.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const loadTestPlans = async () => {
  try {
    const result = await getTestPlans({ page: 1, size: 100 })
    testPlanOptions.value = (result.items || []).map((plan: any) => ({
      id: plan.id,
      name: plan.name
    }))
  } catch (error: any) {
    console.error('加载测试计划失败:', error)
    testPlanOptions.value = []
  }
}

const loadVersions = async () => {
  try {
    const result = await versionAPI.getVersions({ page: 1, size: 200 })
    let versionsData: any[] = []
    
    if (result && result.success && result.data) {
      if (Array.isArray(result.data)) {
        versionsData = result.data
      } else if (typeof result.data === 'object') {
        if ('items' in result.data && Array.isArray(result.data.items)) {
          versionsData = result.data.items
        } else if ('data' in result.data && Array.isArray(result.data.data)) {
          versionsData = result.data.data
        }
      }
    }
    
    versionOptions.value = versionsData.map((v: any) => ({
      id: v.id || v._id,
      name: v.name || '',
      version_number: v.version_number || ''
    })).filter(v => v.id && (v.name || v.version_number))
  } catch (error: any) {
    console.error('加载版本列表失败:', error)
    versionOptions.value = []
  }
}

// 事件处理
const handleSearch = () => {
  pagination.page = 1
  loadTestReports()
}

const handleResetFilter = () => {
  filterForm.search = ''
  filterForm.test_plan_id = ''
  filterForm.version_id = ''
  handleSearch()
}

const handleView = (_report: TestReportListResponse) => {
  ElMessage.info('查看报告详情功能待开发')
}

const handleLinkVersion = (report: TestReportListResponse) => {
  currentReport.value = report
  linkVersionForm.version_id = report.version_id || ''
  linkVersionDialogVisible.value = true
}

const handleSaveLinkVersion = async () => {
  if (!currentReport.value) return
  
  try {
    linking.value = true
    await linkVersion(currentReport.value.id, {
      version_id: linkVersionForm.version_id
    })
    ElMessage.success('关联版本成功')
    linkVersionDialogVisible.value = false
    await loadTestReports()
  } catch (error: any) {
    console.error('关联版本失败:', error)
    ElMessage.error(error?.message || '关联版本失败')
  } finally {
    linking.value = false
  }
}

const handleUploadFile = (report: TestReportListResponse) => {
  currentReport.value = report
  fileList.value = []
  uploadDialogVisible.value = true
}

const beforeUpload = (file: File) => {
  const isValidType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].includes(file.type)
  if (!isValidType) {
    ElMessage.error('只能上传 PDF、Word、Excel 格式的文件')
    return false
  }
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB')
    return false
  }
  return true
}

const handleUploadSuccess = async (response: any) => {
  if (response.success) {
    ElMessage.success('上传文件成功')
    uploadDialogVisible.value = false
    await loadTestReports()
  } else {
    ElMessage.error(response.message || '上传文件失败')
  }
}

const handleUploadError = (error: any) => {
  console.error('上传文件失败:', error)
  ElMessage.error('上传文件失败')
}

const handleDelete = async (report: TestReportListResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除测试报告 "${report.name}" 吗？`,
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    
    await deleteTestReport(report.id)
    ElMessage.success('删除成功')
    await loadTestReports()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除测试报告失败:', error)
      ElMessage.error(error?.message || '删除失败')
    }
  }
}

const handleSizeChange = () => {
  loadTestReports()
}

const handleCurrentChange = () => {
  loadTestReports()
}

// 初始化
onMounted(async () => {
  await loadTestPlans()
  await loadVersions()
  await loadTestReports()
})
</script>

<style scoped lang="scss">
.test-reports-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    .header-left {
      .page-title {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }
      
      .page-description {
        margin: 0;
        font-size: 14px;
        color: #909399;
      }
    }
  }
  
  .filter-section {
    margin-bottom: 20px;
    
    .filter-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .filter-left {
        display: flex;
        gap: 12px;
        align-items: center;
      }
    }
  }
  
  .table-card {
    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
